package com.pkk.components.util.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;

/**
 * @description:
 * @author: peikunkun
 * @create: 2018-10-26 09:47
 **/
public class WebUtil {

  private static final String[] agent = new String[]{"Android", "iPhone", "iPod", "iPad", "Windows Phone",
      "MQQBrowser"};

  public WebUtil() {
  }

  public static Object getSessionAttribute(HttpServletRequest request, String name) {
    HttpSession session = request.getSession(false);
    return session != null ? session.getAttribute(name) : null;
  }

  public static void removeSessionAttribute(HttpServletRequest request, String name) {
    request.getSession().removeAttribute(name);
  }

  public static void clearSessionAttribute(HttpServletRequest request) {
    request.getSession().invalidate();
  }

  public static void setSessionAttribute(HttpServletRequest request, String name, Object value) {
    if (value != null) {
      request.getSession().setAttribute(name, value);
    } else {
      HttpSession session = request.getSession(false);
      if (session != null) {
        session.removeAttribute(name);
      }
    }

  }

  public static void toPageJsonSuccess(String mes, HttpServletResponse response) {
    try {
      toPageJsonMessage(1, mes, response);
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static void toPageJsonFailed(String mes, HttpServletResponse response) {
    try {
      toPageJsonMessage(-1, mes, response);
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static void toPageJsonNoLogin(String mes, HttpServletResponse response) {
    try {
      toPageJsonMessage(98, mes, response);
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static void toPageJsonNoAuth(String mes, HttpServletResponse response) {
    try {
      toPageJsonMessage(99, mes, response);
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static void toPageJsonMessage(int result, String mes, HttpServletResponse response) throws IOException {
    StringBuffer sb = new StringBuffer();
    sb.append("{");
    sb.append("\"result\":\"" + result + "\",");
    sb.append("\"mes\":\"" + mes + "\"");
    sb.append("}");
    response.setContentType("application/json; charset=utf-8");
    PrintWriter out = response.getWriter();
    out.write(sb.toString());
    out.flush();
    out.close();
  }

  public static void toPageJsonMessage(String result, String mes, HttpServletResponse response) throws IOException {
    StringBuffer sb = new StringBuffer();
    sb.append("{");
    sb.append("\"result\":\"" + result + "\",");
    sb.append("\"mes\":\"" + mes + "\"");
    sb.append("}");
    response.setContentType("application/json; charset=utf-8");
    PrintWriter out = response.getWriter();
    out.write(sb.toString());
    out.flush();
    out.close();
  }

  public static void toPageJson(HttpServletResponse response, String message) {
    try {
      response.setContentType("application/json; charset=utf-8");
      PrintWriter out = response.getWriter();
      out.print(message);
      out.flush();
      out.close();
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static void toAppJson(HttpServletResponse response, String mes, Object object) {
    try {
      toAppJsonMessage(1, mes, object, response);
    } catch (IOException var4) {
      var4.printStackTrace();
    }

  }

  public static void toAppJson(HttpServletResponse response, String mes, Object object, Object activityData) {
    try {
      toAppJsonMessage(1, mes, object, activityData, response);
    } catch (IOException var5) {
      var5.printStackTrace();
    }

  }

  public static void toAppJsonMessage(int result, String mes, Object data, Object activityData,
      HttpServletResponse response) throws IOException {
    StringBuffer sb = new StringBuffer();
    sb.append("{");
    sb.append("\"result\":\"" + result + "\",");
    sb.append("\"mes\":\"" + mes + "\",");
    sb.append("\"data\":" + data + ",");
    sb.append("\"activityData\":" + activityData);
    sb.append("}");
    response.setContentType("application/json; charset=utf-8");
    PrintWriter out = response.getWriter();
    out.write(sb.toString());
    out.flush();
    out.close();
  }

  public static void toAppJsonMessage(int result, String mes, Object data, HttpServletResponse response)
      throws IOException {
    StringBuffer sb = new StringBuffer();
    sb.append("{");
    sb.append("\"result\":\"" + result + "\",");
    sb.append("\"mes\":\"" + mes + "\",");
    sb.append("\"data\":" + data);
    sb.append("}");
    response.setContentType("application/json; charset=utf-8");
    PrintWriter out = response.getWriter();
    out.write(sb.toString());
    out.flush();
    out.close();
  }

  public static void toPageXml(HttpServletResponse response, String message) {
    try {
      response.setContentType("application/xml; charset=utf-8");
      PrintWriter out = response.getWriter();
      out.print(message);
      out.flush();
      out.close();
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static void toPageText(HttpServletResponse response, String message) {
    try {
      response.setContentType("text/html; charset=utf-8");
      PrintWriter out = response.getWriter();
      out.print(message);
      out.flush();
      out.close();
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static void toPageTextPlain(HttpServletResponse response, String message) {
    try {
      response.setContentType("text/plain; charset=utf-8");
      PrintWriter out = response.getWriter();
      out.print(message);
      out.flush();
      out.close();
    } catch (IOException var3) {
      var3.printStackTrace();
    }

  }

  public static String InputStreamToString(InputStream a) {
    StringBuilder sb = new StringBuilder();
    String line = null;

    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(a, StandardCharsets.UTF_8));
      line = null;

      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
    } catch (IOException var4) {
      var4.printStackTrace();
    }

    return sb.toString();
  }

  public static boolean intToBoolean(int i) {
    return i == 1;
  }

  public static String getServerPath(HttpServletRequest request) {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName();
    if (80 != request.getServerPort()) {
      basePath = basePath + ":" + request.getServerPort();
    }

    basePath = basePath + path;
    return basePath;
  }

  public static String getCookies(HttpServletRequest request, String name) {
    String result = "";
    Cookie[] cookie = request.getCookies();
    if (cookie == null) {
      return "";
    } else {
      for (int i = 0; i < cookie.length; ++i) {
        Cookie cook = cookie[i];
        if (cook.getName().equals(name)) {
          result = cook.getValue();
        }
      }

      return result;
    }
  }

  public static void setCookies(HttpServletResponse response, String name, String value) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(2592000);
    cookie.setPath("/");
    response.addCookie(cookie);
  }

  public static boolean isInApp(HttpServletRequest request) {
    String referer = request.getHeader("referer");
    String from = request.getParameter("from");
    return referer != null && from == null;
  }

  public static boolean isWeixin(HttpServletRequest request) {
    String ua = request.getHeader("user-agent").toLowerCase();
    return ua.indexOf("micromessenger") > 0;
  }

  private static String TruncateUrlPage(String strURL) {
    String strAllParam = null;
    String[] arrSplit = null;
    strURL = strURL.trim().toLowerCase();
    arrSplit = strURL.split("[?]");
    if (strURL.length() > 1 && arrSplit.length > 1) {
      for (int i = 1; i < arrSplit.length; ++i) {
        strAllParam = arrSplit[i];
      }
    }

    return strAllParam;
  }

  public static int getNetType(String agent) {
    return agent != null && agent.contains("NetType/WIFI") ? 1 : 2;
  }

  public static int getDeviceType(String agent) {
    return agent != null && agent.contains("iPhone") ? 1 : 2;
  }

  public static Map<String, String> urlSplit(String URL) {
    URL = URL.replace("?10000skip=true", "");
    Map<String, String> mapRequest = new HashMap();
    String[] arrSplit = null;
    String strUrlParam = TruncateUrlPage(URL);
    if (strUrlParam == null) {
      return mapRequest;
    } else {
      arrSplit = strUrlParam.split("[&]");
      String[] var4 = arrSplit;
      int var5 = arrSplit.length;

      for (int var6 = 0; var6 < var5; ++var6) {
        String strSplit = var4[var6];
        String[] arrSplitEqual = null;
        arrSplitEqual = strSplit.split("[=]");
        if (arrSplitEqual.length > 1) {
          mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
        } else if (arrSplitEqual[0] != "") {
          mapRequest.put(arrSplitEqual[0], "");
        }
      }

      return mapRequest;
    }
  }

  public static boolean isTxUa(String ua) {
    boolean flag = false;
    Map<String, Object> m = new HashMap();
    m.put(
        "Mozilla/5.0 (Linux; Android 5.1.1; SM801 Build/LMY47V; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043024 Safari/537.36 MicroMessenger/6.5.4.1000 NetType/4G Language/zh_CN",
        1);
    m.put(
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.27.400 QQBrowser/9.0.2524.400",
        1);
    m.put(
        "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27 MicroMessenger/6.5.5 NetType/WIFI Language/zh_CN",
        1);
    m.put(
        "Mozilla/5.0 (Linux; Android 4.4.4; Coolpad Y82-520 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 MicroMessenger/6.5.4.1000 NetType/4G Language/zh_CN",
        1);
    m.put(
        "Mozilla/5.0 (Linux; Android 4.4.4; HUAWEI ALE-CL00 Build/HuaweiALE-CL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043024 Safari/537.36 MicroMessenger/6.5.4.1000 NetType/4G Language/zh_CN",
        1);
    m.put(
        "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27 QQ/6.6.9.412 V1_IPH_SQ_6.6.9_1_APP_A Pixel/750 Core/UIWebView NetType/WIFI",
        1);
    m.put("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0", 1);
    m.put(
        "Mozilla/5.0 (Linux; Android 6.0.1; OPPO R9s Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.9 TBS/036906 Safari/537.36 MicroMessenger/6.5.4.1000 NetType/4G Language/zh_CN",
        1);
    m.put(
        "Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H143 Safari/600.1.4",
        1);
    m.put(
        "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27 MicroMessenger/6.5.5 NetType/WIFI Language/en",
        1);
    m.put(
        "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0)",
        1);
    return m.get(ua) != null ? true : flag;
  }

  public static boolean checkAgentIsMobile(String ua) {
    boolean flag = false;
    if ((!ua.contains("Windows NT") || ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;")) && !ua
        .contains("Windows NT") && !ua.contains("Macintosh")) {
      String[] var2 = agent;
      int var3 = var2.length;

      for (int var4 = 0; var4 < var3; ++var4) {
        String item = var2[var4];
        if (ua.contains(item)) {
          flag = true;
          break;
        }
      }
    }

    return flag;
  }

  public static String getIp2(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
      int index = ip.indexOf(",");
      if (index == -1) {
        return ip;
      }
    }

    ip = request.getHeader("X-Real-IP");
    return StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip) ? ip : request.getRemoteAddr();
  }
}
